# encoding=utf-8
import  sys
import ssl, sys,json
from urllib import request, response, parse

# 获取token
def get_token():
    client_id = "E6ayCt5GqWChmzMH7W87l51R"
    client_secret = "oEGr94qUn08XIF5rhG958ROWvs4EmCRw"
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (
        client_id, client_secret)
    req = request.Request(host)
    req.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = request.urlopen(req)
    # 获得请求结果
    content = response.read()
    # 结果转化为字符
    content = bytes.decode(content)
    # 转化为字典
    content = eval(content[:-1])
    return content['access_token']

# 读取文件内容，转换为base64编码
# 二进制方式打开图文件
def imgdata(file1path):
    import base64
    f = open(r'%s' % file1path, 'rb')
    pic1 = base64.b64encode(f.read())
    f.close()
    params = {"image": pic1}
    return params

# 提交进行对比获得结果
def img(file1path):
    token = get_token()
    # 人脸对比API
    #url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=' + token
    url='https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=' + token
    params = imgdata(file1path)
    # urlencode处理需提交的数据
    data = parse.urlencode(params).encode('utf-8')
    req = request.Request(url=url, data=data)
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = request.urlopen(req)
    content = response.read()
    if content:
        print(content.decode())
img(r'test01.jpg')
